//
//  FlutterWrapperVC.m
//  Project
//
//  Created by liting on 2025/9/9.
//

#import "FlutterWrapperVC.h"
#import "AppDelegate.h"
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
#import "FlutterChannelManager.h"
#import "RecommendVC.h"

static NSString *const kDefaultMethodChannelName = @"com.example/native_channel";
static NSString *const kParametersMethodChannelName = @"com.example/parameters_channel";

@interface FlutterWrapperVC ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer *customSwipeGesture;

@property (nonatomic, strong) FlutterEngine *flutterEngine;
@property (nonatomic, strong) FlutterViewController *flutterViewController;
@property (nonatomic, strong) FlutterMethodChannel *paramsMethodChannel;
@property (nonatomic, strong) FlutterMethodChannel *methodChannel;
@property (nonatomic, copy) NSString *initialRoute;
@property (nonatomic, strong) NSDictionary *initialParams;
@property (nonatomic, assign) BOOL navigationBarHidden;

@end

@implementation FlutterWrapperVC

- (instancetype)initWithRoute:(NSString *)route
                       params:(NSDictionary *_Nullable)params
          navigationBarHidden:(BOOL)navigationBarHidden{
    self = [super init];
    if (self) {
        _initialRoute = route;
        _initialParams = params ?: @{};
        _navigationBarHidden = navigationBarHidden;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:self.navigationBarHidden animated:animated];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:self.navigationBarHidden animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColor.whiteColor;

    [self setupFlutterEngine];
    [self setupFlutterViewController];
    [self setupMethodChannel];

    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self setupSwipeBackGestureListener];
}

- (void)setupSwipeBackGestureListener {
    _customSwipeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleCustomSwipe:)];
    _customSwipeGesture.edges = UIRectEdgeLeft;
    _customSwipeGesture.delegate = self;
}

// 处理自定义侧滑手势
- (void)handleCustomSwipe:(UIScreenEdgePanGestureRecognizer *)gesture {
    CGPoint translation = [gesture translationInView:self.view];
    CGFloat progress = fabs(translation.x / self.view.bounds.size.width);

    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            break;

        case UIGestureRecognizerStateChanged:
            if (progress > 0.3) {
                NSLog(@"超过即将返回");
            }
            break;

        case UIGestureRecognizerStateEnded:
            if (progress > 0.3) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            break;

        case UIGestureRecognizerStateCancelled:
            NSLog(@"侧滑返回被取消");
            break;
        case UIGestureRecognizerStatePossible:

            break;
        case UIGestureRecognizerStateFailed:

            break;
    }
}

- (void)setupFlutterEngine {
    if(self.flutterEngine) return;
    AppDelegate *appDelegate = [AppDelegate sharedInstance];
    FlutterEngineGroupOptions *options = [[FlutterEngineGroupOptions alloc] init];
    options.entrypoint = @"main";
    options.libraryURI = nil;
    options.initialRoute = self.initialRoute;
    self.flutterEngine = [appDelegate.engineGroup makeEngineWithOptions:options];
    [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
    [self.flutterEngine run];
}

- (void)setupFlutterViewController {
    // 创建 FlutterViewController
    self.flutterViewController = [[FlutterViewController alloc]
                                  initWithEngine:self.flutterEngine
                                  nibName:nil
                                  bundle:nil];
    // 设置模态展示样式（解决导航栏问题）
    self.flutterViewController.modalPresentationStyle = UIModalPresentationFullScreen;

    // 添加到当前视图控制器
    [self addChildViewController:self.flutterViewController];
    self.flutterViewController.view.frame = self.view.bounds;
    [self.view addSubview:self.flutterViewController.view];
    [self.flutterViewController didMoveToParentViewController:self];
}

- (void)setupMethodChannel {
    // 公共事件通道
    self.methodChannel = [FlutterMethodChannel
                          methodChannelWithName:kDefaultMethodChannelName
                          binaryMessenger:self.flutterViewController.binaryMessenger];
    __weak typeof(self) weakSelf = self;
    [self.methodChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
        [weakSelf handleMethodCall:call result:result];
    }];

    // 传递参数通道
    self.paramsMethodChannel = [FlutterMethodChannel
                                methodChannelWithName:kParametersMethodChannelName
                                binaryMessenger:self.flutterViewController.binaryMessenger];
    [self.paramsMethodChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
        [weakSelf handleParamsMethodCall:call result:result];
    }];
    // 发送初始参数
    if (self.initialParams) {
        [[FlutterChannelManager sharedManager] setupParams:self.paramsMethodChannel arguments:self.initialParams];
    }
}

// 处理参数事件
- (void)handleParamsMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {

}

// 处理公共事件
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"getPlatformVersion"]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    else if ([call.method isEqualToString:@"popFlutterPage"]) {
        [self.navigationController popViewControllerAnimated:YES];
        result(nil);
    } else if ([call.method isEqualToString:@"addGestureRecognizer"]) {
        [self.view addGestureRecognizer:_customSwipeGesture];
        result(nil);
    } else if ([call.method isEqualToString:@"removeGestureRecognizer"]) {
        [self.view removeGestureRecognizer:_customSwipeGesture];
        result(nil);
    }else if ([@"pushRecommendPage" isEqualToString:call.method]) {
        RecommendVC *view = [[RecommendVC alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:view animated:YES];
    }
    else {
        result(FlutterMethodNotImplemented);
    }
}

- (void)sendMessageToFlutter:(NSString *)method
                   arguments:(id)arguments
                  completion:(void (^)(id))completion {
    [self.methodChannel invokeMethod:method arguments:arguments result:completion];
}

- (void)dealloc {
    NSLog(@"FlutterWrapperViewController dealloc");
    // 销毁引擎
    [self.flutterEngine destroyContext];
}

@end
